from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.urls import reverse

from myapp2.models import UserBaseInfo


def index(request):
    return HttpResponse("myapp2中的index方法")


def show(request, id):
    return HttpResponse("myapp2中的show方法, 参数为id，值为" + str(id))


def show_uuid(request, id):
    return HttpResponse("myapp2中的show_uuid方法, 参数为id，值为" + str(id))


def show_slug(request, q):
    return HttpResponse("myapp2中的show_slug方法, 参数为q，值为" + str(q))


def article_list(request, year):
    return HttpResponse("myapp2中的article_list方法, 参数为year，值为" + str(year))


def article_page(request, page, key):
    return HttpResponse("myapp2中的article_page方法, 参数为page，值为" + str(page) + ", key为" + str(key))


def url_reverse(request):
    # 使用reverse函数获取路由地址，反向解析
    print("在views()函数中，使用reverse()方法解析的结果：" + reverse('myapp2_url_reverse'))
    return render(request, '2/url_reverse.html')


def hello(request):
    return HttpResponse("Hello World")


def test_get(request):
    print(request.get_host())  # 域名 + 端口号
    print(request._get_raw_host())  # 全部路径，包含参数
    print(request.path)  # 获取访问文件路径，不包含参数
    print(request.get_full_path())  # 获取访问文件路径，包含参数
    print(request.method)  # 获取请求中使用的HTTP方式（GET、POST等）
    print(request.GET)  # 获取请求中的GET参数
    print(request.META['HTTP_USER_AGENT'])  # 用户浏览器的user-agent字符串
    print(request.META['REMOTE_ADDR'])  # 客户端的IP地址
    print(request.GET.get('username'))  # 获取get参数
    return HttpResponse()


def test_post(request):
    print(request.POST)  # 获取请求中使用的HTTP方式（GET、POST等）
    print(request.POST.get('username'))  # 获取post参数
    return render(request, '2/test_post.html')


def test_response(request):
    response = HttpResponse()
    response.write("Hello World")
    response.write("<br>")
    response.write(response.content)
    response.write("<br>")
    response.write(response['Content-Type'])
    response.write("<br>")
    response.write(response.status_code)
    response.write("<br>")
    response.write(response.charset)
    response.write("<br>")
    return response


def test_render(request):
    return render(request, '2/test_render.html', {'info': 'Hello World'}, content_type='text/html')


def test_redirect_model(request, id):
    user = UserBaseInfo.objects.get(id=id)
    return redirect(user)


def userinfo(request, id):
    user = UserBaseInfo.objects.get(id=id)
    return HttpResponse("编号：" + str(user.id) + "，姓名：" + user.username)


def test_redirect_views(request, id):
    return redirect('myapp2_userinfo', id)


def test_redirect(request):
    return redirect("https:www.phei.com.cn/")